package com.example.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.domain.model.Borrow;
import com.example.demo.domain.query.BorrowCreateQuery;
import com.example.demo.domain.query.BorrowDtlQuery;
import com.example.demo.domain.vo.BorrowDtlVo;
import com.example.demo.mapper.BookMapper;
import com.example.demo.mapper.BorrowMapper;
import com.example.demo.service.IBorrowService;
import com.example.demo.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BorrowServiceImpl extends ServiceImpl<BorrowMapper, Borrow> implements IBorrowService {
    @Autowired
    private BorrowMapper borrowMapper;
    @Autowired
    private BookMapper bookMapper;
    @Override
    @Transactional
    public int insert(BorrowCreateQuery borrowCreateQuery) {
        // jwt拿到用户id
        borrowCreateQuery.setUserId(JWTUtils.getUserIdByAud());
        //判断该userid的借书次数超过2本
        int borrowCount = borrowMapper.getBorrowCount(borrowCreateQuery.getUserId());
        //借书小于2本
        if (borrowCount >= 2 ){
           return 0;
        }
        //更新图书状态
        bookMapper.updatebookStatus(borrowCreateQuery.getBookId());
        return borrowMapper.insert(borrowCreateQuery);
    }

    @Override
    public List<BorrowDtlVo> dtl(BorrowDtlQuery borrowDtlQuery) {
        return borrowMapper.dtl(borrowDtlQuery);
    }

    @Override
    public int updateBorrowDate(Long borrowId) {
        if (borrowMapper.getRenewCount(borrowId,JWTUtils.getUserIdByAud()) < 3){
            return borrowMapper.updateBorrowDate(borrowId,JWTUtils.getUserIdByAud());
        }
        return 0;
    }

    @Override
    @Transactional //开启事务
    public int returnBooK(Long bookId) {
        //归还日期设置为现在
        borrowMapper.returnTimeBook(bookId,JWTUtils.getUserIdByAud());
        //更新图书状态

        return bookMapper.updateStatus(bookId);
    }


}
